// 生成拓扑图数据
export const generateTopologyData = (config, clusterData, moduleData) => {
  const nodes = [];
  const edges = [];
  const clusterMap = {};

  config.forEach(item => {
    // 处理调用方节点
    if (item.callerCluster && item.callerModule) {
      if (!clusterMap[item.callerCluster]) {
        clusterMap[item.callerCluster] = true;
        const clusterName = clusterData.find(c => c.id === item.callerCluster)?.name || item.callerCluster;
        nodes.push({
          id: `cluster-${item.callerCluster}`,
          type: 'rect',
          label: clusterName,
          size: [180, 120],
          style: { fill: '#f0f0f0', stroke: '#999' },
        });
      }

      const moduleName = moduleData[item.callerCluster]?.find(m => m.id === item.callerModule)?.name || item.callerModule;
      nodes.push({
        id: `${item.callerCluster}-${item.callerModule}`,
        type: 'ellipse',
        label: moduleName,
        parent: `cluster-${item.callerCluster}`,
        size: [100, 60],
        style: { fill: '#fff', stroke: '#1890ff' },
      });
    }

    // 处理被调用方节点
    if (item.calleeCluster && item.calleeModule) {
      if (!clusterMap[item.calleeCluster]) {
        clusterMap[item.calleeCluster] = true;
        const clusterName = clusterData.find(c => c.id === item.calleeCluster)?.name || item.calleeCluster;
        nodes.push({
          id: `cluster-${item.calleeCluster}`,
          type: 'rect',
          label: clusterName,
          size: [180, 120],
          style: { fill: '#f0f0f0', stroke: '#999' },
        });
      }

      const moduleName = moduleData[item.calleeCluster]?.find(m => m.id === item.calleeModule)?.name || item.calleeModule;
      nodes.push({
        id: `${item.calleeCluster}-${item.calleeModule}`,
        type: 'ellipse',
        label: moduleName,
        parent: `cluster-${item.calleeCluster}`,
        size: [100, 60],
        style: { fill: '#fff', stroke: '#1890ff' },
      });
    }

    // 处理调用关系
    if (item.callerCluster && item.callerModule && item.calleeCluster && item.calleeModule) {
      edges.push({
        source: `${item.callerCluster}-${item.callerModule}`,
        target: `${item.calleeCluster}-${item.calleeModule}`,
        label: '调用',
        style: { endArrow: true },
      });
    }
  });

  return { nodes, edges };
};

// 验证拓扑配置是否有效
export const validateTopologyConfig = (config) => {
  if (!config || config.length === 0) return { valid: false, message: '请配置拓扑' };

  const invalidItem = config.find(
    item => !item.callerCluster || !item.callerModule || !item.calleeCluster || !item.calleeModule
  );

  if (invalidItem) return { valid: false, message: '请完善所有拓扑配置项' };

  return { valid: true };
};